const query = require("../db/query");
const datetime = require("silly-datetime");
var iconv = require("iconv-lite");
// const stopIphone = require("../controller/stopIphone");
// const createUUID2 = require("../service/createUID");

// 新项目上传的新提交项目报价数据
const upProjecData = (req, res) => {
  try {
    var dateTime = datetime.format(new Date(), "YYYY-MM-DD HH:mm:ss");
    var formatData2 = req.body;
    var formatData3 = JSON.stringify(req.body);
    var formatData4 = JSON.parse(formatData3); //转一下免除显示 Object: null prototype    //如果拼接字符串里面有变量是需要使用两种冒号
    // console.log("formatData4", formatData4);
    const sql1 = `INSERT INTO baojia_data (`;
    var sql2 = "",
      sql4 = "'",
      D1Toal = 0;
    var datalength = 0;
    for (let k in formatData4) {
      datalength++;
      sql2 += k;
      sql4 += formatData4[k];
      sql2 += ",";
      sql4 += "','";
      D1Toal++;
      var vd = formatData4[k];
      // console.log(k, vd)
    }
    // console.log('datalength', datalength, D1Toal);
    // console.log('formatData4', formatData4)
    var sql22 = sql2; //.substr(0, sql2.length - 1);
    sql22 += "UpdateTime";
    var sql42 = sql4; //.substr(0, sql4.length - 2);
    sql42 += dateTime + "'";
    const sql3 = ") VALUES  (";
    const sql5 = `)`;
    const AllSql = sql1 + sql22 + sql3 + sql42 + sql5;
    query(AllSql)
      .then((data, status, err) => {
        //异步操作数据库后返回到前端数据
        let json = {
          info: data,
          msg: "success",
          code: 200,
          status,
          datalen: formatData3.length,
          path: req.path,
          parms: req.parms,
          query: req.query,
          queryLength: req.query.length,
          err,
        };
        res.json(json);
      })
      .then((res) => {
        // console.log("提交新项目数据保存操作");
        // console.error('err', res)
      })
      .catch(function (res) {
        console.log("upProjecData", res);
        // console.error(res);
        res.json({
          info: data,
          msg: "error",
          code: 100,
          err,
          status,
        });
        return;
      });
  } catch (error) {
    console.log("upProjecDataTryCatch", error);
    res.json(error);
    // console.error(error);
  }
};

// 更新项目的数据 updateProjecData
const updateProjecData = (req, res) => {
  try {
    var dateTime = datetime.format(new Date(), "YYYY-MM-DD HH:mm:ss");
    var formatData3 = JSON.stringify(req.body); //json转字符串
    var formatData4 = JSON.parse(formatData3); //字符串转json，转一下免除显示 Object: null prototype    //如果拼接字符串里面有变量是需要使用两种冒号
    var sid = formatData4.sid;
    var B_userName = req.cookies.userName || null;
    var B_userType = req.cookies.userType || null;
    var cname = req.body.cname || null;
    var delstr = Reflect.deleteProperty(formatData4, "sid"); //剔除不用写入到数据库的，否则会报错
    const sql1 = `UPDATE baojia_data  SET  `;
    var sql2 = "",
      sql22,
      sql4 = "",
      sql42 = "",
      D1Toal = 0;
    for (let k in formatData4) {
      sql2 = k; //字段名
      sql4 = formatData4[k]; //字段数据
      sql22 = sql2 + "='" + sql4 + "',"; //连接字符串
      sql42 += sql22;
      //   console.log(sql2, ":", sql4);
      D1Toal++;
    }
    var updatetime = "UpdateTime";
    sql42 += updatetime + "='" + dateTime + "'";
    const sql6 = ` WHERE sid='${sid}';`; ///sql字符串结尾
    const AllSql = sql1 + sql42 + sql6;
    // console.log("UpdateAllSql:", AllSql);  //此次不用做权限拦截，在请求修改时会查询数据，查询时候做了拦截
    // if (B_userName == userName || userName == cname || B_userType == "admin" || B_userType == "superAdmin" || B_userType == "director" || B_userType == "manager") {
    query(AllSql).then((data, status, err) => {
      //异步操作数据库后返回到前端数据
      console.log("queryRES:", data, status, err);
      let json = {
        info: data,
        msg: "success",
        code: 200,
        status,
        datalen: formatData3.length,
        path: req.path,
        parms: req.parms,
        query: req.query,
        queryLength: req.query.length,
        err,
      };
      if (!err && data != "query数据库连接错误") {
        res.json(json);
      } else {
        res.json({
          info: data,
          msg: "不能填写特殊字符，请检查修改！",
          code: 101,
          status,
          datalen: formatData3.length,
          path: req.path,
          parms: req.parms,
          query: req.query,
          queryLength: req.query.length,
          err,
        });
      }
    });
    // } else {
    //     res.json({
    //         info: "无授权！",
    //         msg: "非管理员或经理不能修改其他项目数据！",
    //         code: 101,
    //         path: req.path,
    //         parms: req.parms,
    //         query: req.query,
    //         queryLength: req.query.length,
    //         err,
    //     });
    // }
  } catch (error) {
    console.log("updateProjecData", error);
    res.json(error);
  }
};

//获取首页数据
var count = 0;
const getLdData = (req, res) => {
  try {
    // 获取当前访问用户的uuid
    let uuid = req.cookies.uuid;
    // console.log('req:',req.body);
    if (
      JSON.stringify(req.body) == "{}"
      //   req.body == null ||
      //   req.body == ""
      //   req.body == undefined ||
      //   isNaN(req.body)
    ) {
      // console.log(req);
      res.json({
        info: " 参数错误",
        code: 201,
        msg: "请检查参数或联系管理员",
        status,
      });
    } else {
      //获取倒数前10条数数据
      var formatData12 = JSON.stringify(req.body); //json转字符串
      var formatData22 = JSON.parse(formatData12); //字符串转json，
      // console.log("req:", req.body);
      var start = formatData22.start;
      var len = formatData22.len || 10;
      // console.log(start, len);
      const sql = "select * from baojia_data order by ID desc limit " + `${start} , ${len}`; //AND from_type='client'  加此仅获取客户自己发的
      const sql2 = "SELECT COUNT(*) FROM baojia_data";
      // console.log(sql);
      var info;
      query(sql2).then((data, status, err) => {
        //query数据库连接错误0
        // console.log(data.length);
        if (data.length > 0) {
          //   console.log("总项目数：", data[0]["COUNT(*)"], data.length);
          count = data[0]["COUNT(*)"];
          info = "查询总数成功";
          query(sql).then((data, status, err) => {
            let json = {
              code: 200,
              msg: "success",
              data: data,
              status,
              err,
              count: count,
              info,
            };
            // console.log('首次请求首页数据:', data[0])
            if (err || data == "query数据库连接错误0" || data.length < 1) {
              res.json({
                info: "未有查询到数据",
                code: 201,
                msg: "数据库没有数据或数据库操作错误！",
                status,
                err,
              });
            } else {
              res.json(json);
            }
          });
        } else {
          res.json({
            info: " 未有查询到数据",
            code: 201,
            msg: "数据库没有数据！",
            status,
          });
        }
      });
    }
  } catch (error) {
    res.json(error);
  }
};

//获取SID数据接口
const getSid = (req, res) => {
  try {
    //不用数据库操作
    console.log("getsid", req.body);
    var timestamp_sid = new Date().valueOf();
    let json = {
      code: 200,
      msg: "success",
      Sid: timestamp_sid,
    };
    // console.log("首次sid数据:", timestamp_sid);
    res.cookie("sid", timestamp_sid, {
      maxAge: 365 * 24 * 60 * 60 * 1000,
      httpOnly: false,
    });
    res.json(json);
  } catch (error) {
    res.json(error);
  }
};

//删除单条项目数
const deleteProjectData = (req, res) => {
  try {
    // 获取当前访问用户的uuid
    // let uuid = req.cookies.uuid;
    console.log("req:", req.body.sid); //获取倒数前10条数数据   DELETE FROM `baojia_data` WHERE `baojia_data`.`ID` = 224
    //   DELETE FROM `baojia_data` WHERE `baojia_data`.`sid` = 1646475115214
    var sid = req.body.sid;
    var B_userName = req.cookies.userName || null;
    var B_userType = req.cookies.userType || null;
    var cname = req.body.cname || null;
    //   const getType = req.body.getType;
    const sql0 = `SELECT *FROM baojia_data WHERE sid ='${sid} '`;
    query(sql0).then((data, status, err) => {
      if (data == "query数据库连接错误0") {
        res.json({
          code: 100,
          msg: "数据库链接错误",
          err,
          status,
        });
      } else {
        const userName = data[0].engineer || "其他工程师";
        // const userType = data[0].userType || null;
        // console.log(userName, userType, B_userName, B_userType); //B_userName == userName || userName == cname ||除了管理员级别以上的也不能删除自己项目
        if (B_userType == "admin" || B_userType == "superAdmin" || B_userType == "director" || B_userType == "manager") {
          if (sid !== "" && sid !== null && sid !== undefined) {
            const sql = "DELETE FROM `baojia_data` WHERE `baojia_data`.`sid`=" + `${sid}` + ""; //AND from_type='client'  加此仅获取客户自己发的
            query(sql).then((data, status, err) => {
              let json = {
                code: 200,
                info: "删除成功",
                msg: "success",
                status,
                data: data,
                err,
              };
              // console.log('首次请求首页数据:', data[0])
              res.json(json);
              // console.log(data[0].id, data.length)
            });
            // console.log("sql:", sql);
          } else {
            res.json({
              code: 100,
              msg: "参数错误" + status,
              info: "操作失败",
            });
          }
        } else {
          res.json({
            B_userName,
            B_userType,
            cname,
            code: 101,
            msg: "除管理员外，你无权删除其他人的项目数据！该项目负责人是" + userName,
            status,
            info: "该项目负责人是" + userName,
          });
        }
      }
    });
  } catch (error) {
    res.json(error);
  }
};

// 查看项目书-分享页面、查看单个项目、获取老项目数据 和修改项目时候进行权限检测
const checkoneController = (req, res) => {
  // res.sendFile(path.join(process.cwd(), "views", "toview.html"));
  // var checkId = req.params.sid;
  var sid = req.query.sid;
  // var uuid = req.cookies.uuid;
  //   console.log("req.body:", req.body);
  var B_userName = req.cookies.userName || null;
  // var B_cname = req.cookies.cname || null; //获取的中文乱码
  var B_cname = req.body.cname || req.cookies.cname || null;
  var buf = new Buffer(B_cname, "binary");
  var str = iconv.decode(buf, "GBK");

  //   console.log("cookies", str);
  //   console.log("req", req.body.cname);
  var B_userType = req.cookies.userType || null;
  const getType = req.body.getType || "checkOne";
  try {
    const sql = `SELECT *FROM baojia_data WHERE sid ='${sid}' order by ID desc `;
    // const sql2=`SELECT * FROM clients WHERE uuid ='${uuid}';`
    res.cookie("sid", sid, {
      maxAge: 365 * 24 * 60 * 60 * 1000,
      httpOnly: false,
    });
    query(sql).then((data, status, err) => {
      //异步操作数据库后返回到前端数据
      let json = {
        info: data,
        msg: "success",
        code: 200,
        status,
        err,
        // path: req.path, (a !== undefined && a !== null) ? a : b
      };
      var engineer = data.length < 1 ? data[0] : 0;
      // console.log("query查询Sid数据：", data, data.length);
      // console.log("sqlQueryRES:", data, status, err);
      if (err || data == "query数据库连接错误0") {
        let json2 = {
          info: data,
          err,
          status,
          code: 100,
          msg: "参数错误！",
        };
        res.json(json2);
        return json2;
      } else if (data.length < 1 || data == null || data == "" || data == "null") {
        // console.log("checkOne-data", data);
        res.json({
          code: 101,
          msg: "该条数据已经不存在！可能已经被删除，请返回主页查看！",
          info: "error",
          status,
        });
      } else {
        //判断是新增还是更新
        var projcetStatus = data[0].status || "待审批";
        // console.log("checkoneController:", projcetStatus);
        var S_engineer = data[0].engineer || null; //查询出的用户名
        // console.log("查看单个sid项目数据：", S_engineer, B_userName, B_cname, B_userType);
        if (getType == "change") {
          if (projcetStatus == "待审批") {
            //   if (getType == "change") {
            if (S_engineer == B_userName || B_cname == S_engineer || B_userType == "admin" || B_userType == "superAdmin" || B_userType == "superAdmin" || B_userType == "director" || B_userType == "manager") {
              //判断是否有权限更新
              res.json(json);
            } else {
              res.json({
                code: 100,
                msg: "非管理员或经理以上级别你无权修改其他人的项目数据！",
                info: "NO change",
                status,
              });
            }
            //   } else {
            //     //都没问题直接返回
            //
            //   }
          } else {
            res.json({
              code: 101,
              msg: "该项目已经被审批冻结！你不能修改，确要修改请联系系统管理员！",
              info: status,
              status: "error",
              sid,
            });
          }
        } else {
          res.json(json);
        }
      }
    });
  } catch (error) {
    console.log("checkoneController", error);
    res.json({
      code: 100,
      msg: "mysqlError",
      error,
    });
  }
};

// 修改数据之前获取老数据接口
const edithGetController = (req, res) => {
  // res.sendFile(path.join(process.cwd(), "views", "toview.html"));
  var checkId = req.params.sid;
  var sid = req.query.sid;
  var uuid = req.cookies.uuid;
  // console.log("req.body：", req.body)
  try {
    const sql = `SELECT *FROM baojia_data WHERE sid ='${sid} '`;
    // const sql2=`SELECT * FROM clients WHERE uuid ='${uuid}';`
    query(sql).then((data, status, err) => {
      //异步操作数据库后返回到前端数据
      let json = {
        info: data,
        msg: "success",
        code: 200,
        status,
        err,
        // path: req.path,
      };
      // console.log("query查询Sid数据：", data);
      // console.log("sqlQueryRES:", data, status, err);
      if (err || data == null || data == "") {
        let json2 = {
          info: data,
          err,
          status,
          code: 100,
          msg: "参数错误！",
        };
        res.json(json2);
        return json2;
      } else {
        res.json(json);
      }
    });
  } catch (error) {
    console.log("edithGetController", error);
  }
};

// 审批接口
const auditingContorller = (req, res) => {
  try {
    // var checkId = req.params.sid;
    var sid = req.body.sid || "";
    // var csid = req.cookies.sid || "";
    // var uuid = req.cookies.uuid;
    // console.log("req.body：", req.body);
    // var B_cname = req.cookies.cname || null;
    var B_userName = req.cookies.userName || null;
    var B_cname = req.body.cname || req.cookes.cname || "admin";
    // console.log("B_cname", B_cname);
    var B_userType = req.cookies.userType || "user";
    // const getType = req.body.getType;
    const sql = `SELECT *FROM baojia_data WHERE sid ='${sid} '`;
    const sql1 = `UPDATE baojia_data  SET status='已审批'`;
    const sql3 = `, Approver='${B_cname}'`;
    const sql32 = ` WHERE sid='${sid}'`; ///sql字符串结尾
    const sql4 = sql1 + sql3 + sql32;
    // console.log('sql4:', sql4)
    if (sid == "" || sid == null || sid == undefined || sid == "null") {
      res.json({
        code: 102,
        msg: "SID参数错误!",
        info: "error",
        sid,
      });
    } else {
      query(sql).then((data, status, err) => {
        if (err || data == "query数据库连接错误0" || data.length < 1) {
          let json = {
            info: data,
            err,
            status,
            code: 100,
            msg: "参数错误！",
            sid,
          };
          res.json(json);
        } else {
          var engineer = data[0].engineer || null; //审批只能是管理员级别以上，自己也不能审批自己
          if (B_userType == "superAdmin" || B_userType == "admin" || B_userType == "director" || B_userType == "manager") {
            query(sql4).then((data, status, err) => {
              if (err || data == "query数据库连接错误0") {
                let json2 = {
                  info: data,
                  err,
                  status,
                  code: 100,
                  msg: "参数错误！",
                  sid,
                };
                res.json(json2);
                return json2;
              } else if (data.length < 1 || data == null || data == "" || data == "null") {
                res.json({
                  code: 101,
                  msg: "该条数据已经不存在！可能已经被删除，请返回主页查看！",
                  info: "error",
                  status,
                  sid,
                });
              } else {
                let json = {
                  info: data,
                  msg: "审批成功！",
                  code: 200,
                  status: "success",
                  err,
                  sid,
                };
                res.json(json);
              }
            });
          } else {
            let json = {
              info: "权限不够！",
              msg: "除非管理员级别以上，否则你无权进行审批！",
              code: 101,
              status: "error",
              sid,
            };
            res.json(json);
          }
        }
      });
    }
  } catch (error) {
    console.log("auditingContorller", error);
  }
};

// 查询关键词接口
const seachController = (req, res) => {
  try {
    var seachWord = req.body.seachWord || "项目";
    const sql = `SELECT * , baojia_data.projectName FROM   baojia_data WHERE  projectName LIKE '%${seachWord}%' ORDER BY ID ;`;
    // console.log("req:", req.body);
    // console.log("sql:", sql, seachWord);
    query(sql).then((data, status, err) => {
      //   console.log("data", data);
      if (data == "query数据库连接错误0") {
        res.json({
          code: 100,
          msg: "数据库查询错误",
          info: data,
          err,
          status,
          data: null,
        });
      } else {
        res.json({
          code: 200,
          msg: "数据库查询成功",
          data: data,
          err,
          status,
          info: "success",
        });
      }
    });
  } catch (error) {
    res.json(error);
  }
};

// 定制项目上传数据接口
const desiProjectApi = (req, res) => {
  try {
    // console.log("定制项目数据：", req.body);
    var dateTime = datetime.format(new Date(), "YYYY-MM-DD HH:mm:ss");
    var formatData2 = req.body;
    var formatData3 = JSON.stringify(req.body);
    var formatData4 = JSON.parse(formatData3); //转一下免除显示 Object: null prototype    //如果拼接字符串里面有变量是需要使用两种冒号
    const sql1 = `INSERT INTO baojia_data (`;
    var sql2 = "",
      sql4 = "'",
      D1Toal = 0;
    var datalength = 0;
    for (let k in formatData4) {
      datalength++;
      sql2 += k;
      sql4 += formatData4[k];
      sql2 += ",";
      sql4 += "','";
      D1Toal++;
      var vd = formatData4[k];
      // console.log(k, vd)
    }
    // console.log('datalength', datalength, D1Toal);
    // console.log("formatData4", formatData4);
    var sql22 = sql2; //.substr(0, sql2.length - 1);
    sql22 += "UpdateTime";
    var sql42 = sql4; //.substr(0, sql4.length - 2);
    sql42 += dateTime + "'";
    const sql3 = ") VALUES  (";
    const sql5 = `)`;
    const AllSql = sql1 + sql22 + sql3 + sql42 + sql5;
    // console.log(AllSql);
    query(AllSql)
      .then((data, status, err) => {
        //异步操作数据库后返回到前端数据
        let json = {
          info: data,
          msg: "success",
          code: 200,
          status,
          datalen: formatData3.length,
          path: req.path,
          parms: req.parms,
          query: req.query,
          queryLength: req.query.length,
          err,
        };
        res.json(json);
      })
      .then((res) => {
        // console.log("提交新定制项目数据保存操作");
        // console.error('err', res)
      })
      .catch(function (res) {
        console.log("desiProjectApi", res);
        // console.error(res);
      });
  } catch (error) {
    res.json(error);
  }
};

// 修改密码接口---------------------
const changePasswd = (req, res) => {
  // 获取当前访问用户的uuid
  try {
    // console.log("修改密码请求：", req.body);
    // console.log("修改密码请求2:", req)
    var json = {};
    // var formatData1 = JSON.stringify(req.query); //json转字符串
    var formatData1 = JSON.stringify(req.body); //json转字符串
    var formatData2 = JSON.parse(formatData1); //字符串转json，
    // var uuid1 = req.cookies.uuid || "0";
    var userName = formatData2.oldName || null;
    var newName = formatData2.newName || null;
    var postPassword = formatData2.oldPassWord || null;
    var newPassWord = formatData2.newPassWord || null;
    var newPassWord2 = formatData2.newPassWord2 || null;
    if (newPassWord !== newPassWord2) {
      console.log("两次密码不同");
      res.json({
        code: 100,
        msg: "两次输入密码不相同",
      });
    } else {
      // remember = formatData2.rememberme || null;
      //   const sqld1 = `SELECT * FROM  user  WHERE  userName ='` + `${userName}` + "'"; //mysql不能又空格
      const sqld1 = `SELECT * FROM  user  WHERE  userName ='` + `${userName}` + "'"; //mysql不能又空格
      //   console.log("sqld1:", sqld1);
      query(sqld1).then((data, status, err) => {
        json = {};
        // console.log("checkUser:", data);
        if (data == "query数据库连接错误0") {
          json.code = 100;
          json.info = data;
          json.status = status;
          json.msg = data;
          json.data = data;
          json.err = err;
          res.json(json);
        } else if (data == null || data == [""] || data == "" || data.length < 1 || data == "null" || data == "[]" || data == []) {
          json.code = 100;
          json.msg = "用户不正确";
          json.status = status;
          json.info = "用户查询失败";
          json.data = data;
          json.err = err;
          res.json(json);
        } else if (data.length > 0) {
          const userStatus = data[0].userStatus || 0;
          //   console.log("login:", data);
          if (userStatus == "1") {
            json.code = 200;
            json.msg = "用户正确";
            json.userStatus = userStatus;
            console.log("用户正确", data[0].userName);
            // console.log("查询用户类别成功:", data[0].userType);
            var OLDpassword = data[0].passWord || null;
            if (postPassword == OLDpassword) {
              json.msg = "密码验证通过！";
              json.code = 200;
              json.info = status;
              const sql1 = `UPDATE user  SET  `;
              var id = data[0].Id;
              var password = newPassWord;
              var userName = newName;
              const sql3 = ` WHERE ID='${id}';`; ///sql字符串结
              var sql4 = sql1 + `userName='${userName}',passWord='${password}'` + sql3;
              // console.log("sql4:", sql4);
              query(sql4).then((resDats, status, err) => {
                if (data !== "query数据库连接错误0" || resDats.length > 0) {
                  // console.log("修改密码成功：", resDats);
                  json.res = resDats;
                  res.cookie("userName", "", {});
                  res.cookie("uuid", "", {});
                  res.json(json);
                } else {
                  console.log("修改密码失败：", resDats);
                  json.msg = "修改密码失败";
                  json.code = 100;
                  res.json(json);
                }
              });
            } else {
              json.code = 100;
              json.info = data;
              json.status = status;
              json.msg = "密码错误！";
              res.json(json);
            }
          } else {
            res.json({
              code: 100,
              msg: "用户过期！",
              info: status,
            });
          }
        } else {
          res.json({
            code: 100,
            msg: "未有查到该用户",
            info: status,
          });
        }
      });
      // res.json({
      //     code: 200,
      //     msg: "收到密码请求修改数据"
      // })
    }
  } catch (error) {
    res.json(error);
  } finally {
  }
};

// 暴露入口
module.exports = {
  getLdData,
  getSid,
  upProjecData,
  updateProjecData,
  deleteProjectData,
  auditingContorller,
  checkoneController,
  edithGetController,
  seachController,
  desiProjectApi,
  changePasswd,
};

// const path = require("path");
// const query = require("../db/query");
// const mysqlWrite = require("../db/db");
